<template>
  <div>
    <div class="p-6">
      <div class="flex justify-between items-center mb-4">
        <h1 class="text-2xl font-bold text-gray-800">知识库</h1>
        <div class="flex gap-2">
          <button class="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700" @click="openBrush">刷题模式</button>
          <button class="bg-blue-600 text-white px-4 py-2 rounded" @click="openNew">新建知识点</button>
        </div>
      </div>

      <div class="flex gap-4">
        <aside class="w-80 flex-none bg-white rounded p-4 shadow overflow-auto h-[calc(100vh-48px)]">

          <KnowledgeFolderTree @select="onFolderSelect" @drop="onFolderDrop" />
          <div class="mt-4">
            <div class="font-semibold text-gray-700 mb-2">筛选</div>
            <input v-model="keyword" class="border rounded px-3 py-2 w-full" placeholder="搜索标题..." />
            <button class="mt-3 w-full border rounded px-3 py-2" @click="load">搜索</button>

          </div>
          <div class="mt-4 pt-4 border-t">
             <div class="cursor-pointer px-2 py-1 rounded hover:bg-gray-100 flex items-center gap-2" 
                  :class="{ 'bg-blue-50 text-blue-600': selectedFolderId === 'trash' }"
                  @click="onFolderSelect('trash')">
               <span class="text-lg">🗑️</span>
               <span>草稿箱</span>
             </div>
             <button v-if="selectedFolderId === 'trash'" class="mt-2 w-full border rounded px-3 py-2 text-red-600 border-red-200 hover:bg-red-50 text-sm" @click="emptyTrash">清空草稿箱</button>
          </div>
        </aside>

        <div class="flex-1">
          <!-- 顶部面包屑导航（参照问题列表） -->
          <div class="mb-3 text-sm text-gray-600">
            <span class="font-semibold text-gray-700">当前位置：</span>
            <template v-if="breadcrumb.length">
              <span v-for="(b, idx) in breadcrumb" :key="b.id">
                <button class="hover:underline" @click="onFolderSelect(b.id)">{{ b.name }}</button>
                <span v-if="idx < breadcrumb.length - 1"> / </span>
              </span>
            </template>
            <template v-else>全部</template>
          </div>

          <div class="bg-white rounded shadow overflow-x-auto">
            <table class="min-w-full table-fixed">
              <thead>
                <tr class="border-b bg-gray-50 text-left text-sm text-gray-600">
                  <th class="p-3">标题</th>
                  <th class="p-3 w-48 text-center whitespace-nowrap">时间</th>
                  <th class="p-3 w-24 text-center">操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="k in filtered" :key="k.id" class="border-b hover:bg-gray-50"
                    draggable="true"
                    @dragstart="onDragStart(k, $event)">
                  <td class="p-3 align-top cursor-pointer" @click="openKnowledgeDetail(k)">
                    <div class="font-medium text-gray-800">{{ k.title }}</div>
                    <div class="text-sm text-gray-600 mt-1 line-clamp-2">{{ stripHtml(k.summary) }}</div>
                  </td>
                  <td class="p-3 text-sm text-gray-500 text-center whitespace-nowrap align-top">{{ new Date(k.created_at).toLocaleString() }}</td>
                  <td class="p-3 text-sm text-center align-top relative" @click.stop>
                    <button class="p-1 rounded hover:bg-gray-100" @click="toggleRowMenu(k.id)" title="更多">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4 text-gray-600">
                        <path d="M6 10a2 2 0 11-4 0 2 2 0 014 0zm6 0a2 2 0 11-4 0 2 2 0 014 0zm6 0a2 2 0 11-4 0 2 2 0 014 0z"/>
                      </svg>
                    </button>
                    <div v-if="openMenuId===k.id" class="absolute z-10 mt-1 right-2 w-28 bg-white border rounded shadow">
                      <template v-if="selectedFolderId === 'trash'">
                        <button class="w-full text-left px-3 py-2 hover:bg-gray-100" @click="restore(k.id); closeRowMenu()">还原</button>
                        <button class="w-full text-left px-3 py-2 text-red-600 hover:bg-gray-100" @click="hardDelete(k.id); closeRowMenu()">彻底删除</button>
                      </template>
                      <template v-else>
                        <button class="w-full text-left px-3 py-2 hover:bg-gray-100" @click="edit(k); closeRowMenu()">编辑</button>
                        <button class="w-full text-left px-3 py-2 hover:bg-gray-100" @click="moveToFolder(k.id); closeRowMenu()">移动</button>
                        <button class="w-full text-left px-3 py-2 text-red-600 hover:bg-gray-100" @click="remove(k.id); closeRowMenu()">删除</button>
                      </template>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Dialog: 新建/编辑 知识点 -->
      <div v-if="show" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="close">
        <div class="bg-white rounded-lg shadow-2xl ring-1 ring-black/5 w-full max-w-3xl flex flex-col" style="height: 80vh; max-height: 80vh;">
          <div class="px-6 py-4 bg-white border-b flex-shrink-0">
            <h2 class="text-lg font-semibold">{{ form.id ? '编辑知识点' : '新建知识点' }}</h2>
          </div>
          <div class="px-6 py-4 space-y-4 flex-1" style="overflow-y: auto; min-height: 0;">
            <input v-model="kpName" class="border rounded px-3 py-2 w-full" placeholder="知识点名称*" />
            <RichTextEditor v-model="kpDesc" :height="180" />

            <div class="flex items-center justify-between">
              <div class="font-semibold text-gray-800">问题卡片</div>
              <button class="px-3 py-1 border rounded" @click="addCard">添加问题</button>
            </div>

            <div class="space-y-2">
              <div v-for="(card, idx) in qaCards" :key="card.id" class="border rounded">
                <div class="flex items-center justify-between px-3 py-2 bg-gray-50 cursor-pointer" @click="activateCard(idx)">
                  <div class="truncate text-sm text-gray-800">
                    {{ card.question || `问题 ${idx+1}` }}
                  </div>
                  <div class="flex items-center gap-2">
                    <span class="text-xs text-gray-500">{{ card.active ? '编辑中' : '已折叠' }}</span>
                    <button v-if="card.active" class="p-1 text-gray-600 hover:bg-gray-100 rounded" @click.stop="collapseCard(idx)" title="收起">收起</button>
                    <button class="p-1 text-red-600 hover:bg-red-50 rounded" @click.stop="removeCard(idx)" title="删除">✕</button>
                  </div>
                </div>
                <div v-if="card.active" class="p-3 space-y-3">
                  <input v-model="card.question" class="border rounded px-3 py-2 w-full" placeholder="请输入问题" />
                  <RichTextEditor v-model="card.answerHtml" :height="220" />
                </div>
              </div>
            </div>

            <div class="text-sm">
              <label class="block mb-1 text-gray-600">选择目录</label>
              <select v-model="formFolderId" class="border rounded px-3 py-2 w-full">
                <option v-for="f in folderOptions" :key="f.id" :value="f.id">{{ f.label }}</option>
              </select>
            </div>
          </div>
          <div class="px-6 py-4 flex justify-end gap-3 bg-white border-t flex-shrink-0">
            <button class="px-4 py-2 border rounded" @click="close">取消</button>
            <button class="px-4 py-2 bg-blue-600 text-white rounded" @click="submit">保存</button>
          </div>
        </div>
      </div>

      <!-- Drawer: 知识点详情（右侧滑入） -->
      <transition name="drawer-slide">
        <div v-if="detailOpen" class="fixed inset-0 z-40">
          <div class="absolute inset-0 bg-black/40" @click="closeDetail"></div>
          <div class="absolute right-0 top-0 h-full w-3/4 bg-white shadow-2xl p-6 overflow-auto">
            <div class="flex items-center justify-between mb-4">
              <h2 class="text-xl font-semibold text-gray-800">知识点详情</h2>
              <!-- Close button removed as requested -->
            </div>
            <div class="space-y-4">
              <input v-model="dName" class="border rounded px-3 py-2 w-full" placeholder="知识点名称*" />
              <RichTextEditor v-model="dDesc" :height="180" />

              <div class="flex items-center justify-between">
                <div class="font-semibold text-gray-800">问题卡片</div>
                <button class="px-3 py-1 border rounded" @click="dAddCard">添加问题</button>
              </div>

              <div class="space-y-2">
                <!-- 问题卡片列表 -->
                <div v-for="(card, idx) in dCards" :key="card.id" class="border rounded" :data-id="card.id">
                  <div class="flex items-center justify-between px-3 py-2 bg-gray-50 cursor-pointer" @click="dToggleCard(idx)">
                    <div class="truncate text-sm text-gray-800 font-medium">
                      {{ card.question || `问题 ${idx+1}` }}
                    </div>
                    <div class="flex items-center gap-2">
                       <!-- Review Stats -->
                      <div v-if="card.review_stats" class="text-xs text-gray-500 bg-white border rounded px-2 py-0.5 flex items-center gap-1 flex-shrink-0 cursor-help" :title="'上次复盘: ' + (card.review_stats.last_reviewed ? new Date(card.review_stats.last_reviewed).toLocaleString() : '从未')">
                        <span>🔄 {{ card.review_stats.count || 0 }}</span>
                      </div>
                      <button class="p-1 text-blue-600 hover:bg-blue-50 rounded" @click.stop="openAddToReview(card)" title="加入复盘计划">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 11v4m0 0v4m0-4h4m-4 0H8" />
                        </svg>
                      </button>
                      <button class="p-1 text-gray-600 hover:bg-gray-100 rounded" @click.stop="openHistory(card)" title="答题记录">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                      </button>
                      <span class="text-xs text-gray-500">{{ card.active ? '展开' : '折叠' }}</span>
                      <button class="p-1 text-gray-600 hover:bg-gray-100 rounded" @click.stop="dToggleCard(idx)">
                        <svg v-if="card.active" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" /></svg>
                        <svg v-else xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" /></svg>
                      </button>
                      <button class="p-1 text-red-600 hover:bg-red-50 rounded" @click.stop="dRemoveCard(idx)" title="删除">✕</button>
                    </div>
                  </div>
                  <div v-if="card.active" class="p-3 space-y-3">
                    <input v-model="card.question" class="border rounded px-3 py-2 w-full" placeholder="请输入问题" />
                    <RichTextEditor v-model="card.answerHtml" :height="220" :id="`answer-editor-${card.id}`" @ready="onEditorReady(card)" />
                  </div>
                </div>
              </div>

              <div class="flex justify-end gap-3 mt-4">
                <button class="px-4 py-2 border rounded" @click="closeDetail">取消</button>
                <button class="px-4 py-2 bg-blue-600 text-white rounded" @click="saveDetail">保存</button>
              </div>
            </div>
          </div>
        </div>
      </transition>

      <!-- 目录选择器（参照问题模块） -->
      <div v-if="pickFolderOpen" class="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg shadow-2xl ring-1 ring-black/5 w-full max-w-2xl max-h-[80vh] flex flex-col">
          <div class="px-5 pt-5 pb-3 border-b sticky top-0 bg-white z-10">
            <div class="text-lg font-semibold">选择目录</div>
          </div>
          <div class="p-5 overflow-auto">
            <KnowledgeFolderTree @select="onPickSelect" />
            <div class="mt-3 text-xs text-gray-500 break-all">
              <span class="font-semibold text-gray-600">将要选择：</span>{{ tempFolderPath || '未选择' }}
            </div>
          </div>
          <div class="px-5 py-4 flex justify-end gap-3 border-t sticky bottom-0 bg-white z-10">
            <button class="px-4 py-2 border rounded" @click="closeFolderPicker">取消</button>
            <button class="px-4 py-2 bg-blue-600 text-white rounded" :disabled="!tempSelectedFolderId" @click="confirmFolderPicker">确定</button>
          </div>
        </div>
      </div>

      <!-- Add to Review Dialog -->
      <div v-if="showAddToReview" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50" @click.self="closeAddToReview">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
          <h3 class="text-lg font-bold text-gray-800 mb-4">加入复盘计划</h3>
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">复盘策略</label>
              <select v-model="reviewPlanType" class="w-full border rounded px-3 py-2">
                <option value="ebbinghaus">艾宾浩斯遗忘曲线</option>
                <option value="daily">每天 (未来30天)</option>
                <option value="weekly">每周 (未来12周)</option>
                <option value="monthly">每月 (未来12月)</option>
                <option value="custom">自定义间隔</option>
              </select>
            </div>
            <div v-if="reviewPlanType === 'custom'">
              <label class="block text-sm font-medium text-gray-700 mb-1">间隔天数</label>
              <input type="number" v-model.number="reviewCustomInterval" class="w-full border rounded px-3 py-2" min="1" />
            </div>
          </div>
          <div class="mt-6 flex justify-end gap-3">
            <button class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded" @click="closeAddToReview">取消</button>
            <button class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700" @click="confirmAddToReview">确定</button>
          </div>
        </div>
      </div>

      <BrushModal :show="brushOpen" :initial-folder-id="selectedFolderId !== 'trash' ? selectedFolderId : null" @close="brushOpen = false" />
      <AnswerHistoryModal :show="historyOpen" :knowledge-id="detailId" :card-id="historyCardId" @close="historyOpen = false" />

    </div>
  </div>
 </template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import api from '../api'
import KnowledgeFolderTree from '../components/KnowledgeFolderTree.vue'
import { useKnowledgeFolderStore } from '../stores/knowledgeFolders'
import RichTextEditor from '../components/RichTextEditor.vue'
import BrushModal from '../components/BrushModal.vue'
import AnswerHistoryModal from '../components/AnswerHistoryModal.vue'

const list = ref([])
const keyword = ref('')
const selectedFolderId = ref(null)
const folderStore = useKnowledgeFolderStore()
const draggingKnowledgeId = ref(null)
const show = ref(false)
const form = ref({ id: null, title: '', summary: '', body: '' })
// 新建知识点字段
const kpName = ref('')
const kpDesc = ref('')
const qaCards = ref([]) // { id, question, answerHtml, active }
const formFolderId = ref(null)

const filtered = computed(() => list.value.filter(k => !keyword.value || k.title.includes(keyword.value)))
const folderOptions = computed(() => {
  const out = []
  const walk = (nodes, depth) => {
    for (const n of nodes) {
      out.push({ id: n.id, label: `${'\u00A0'.repeat(depth*2)}${n.name}` })
      if (n.children && n.children.length) walk(n.children, depth+1)
    }
  }
  walk(folderStore.tree || [], 0)
  return out
})

// 选中目录的路径（从根到当前）
const selectedPath = computed(() => {
  if (!selectedFolderId.value) return []
  const map = new Map(folderStore.flat.map(f => [f.id, f]))
  const path = []
  let cur = map.get(selectedFolderId.value)
  while (cur) { path.push(cur.name); cur = cur.parent_id ? map.get(cur.parent_id) : null }
  return path.reverse()
})

// 面包屑（对象数组），可点击切换
const breadcrumb = computed(() => {
  const id = selectedFolderId.value
  if (!id) return []
  const map = new Map(folderStore.flat.map(f => [f.id, f]))
  const path = []
  let cur = map.get(id)
  while (cur) { path.unshift(cur); cur = cur.parent_id ? map.get(cur.parent_id) : null }
  return path
})

// 目录选择器与路径（用于新建知识点对话框）
const pickFolderOpen = ref(false)
const tempSelectedFolderId = ref(null)
const formFolderPath = computed(() => {
  if (!formFolderId.value) return ''
  const map = new Map(folderStore.flat.map(f => [f.id, f]))
  const names = []
  let cur = map.get(formFolderId.value)
  while (cur) { names.push(cur.name); cur = cur.parent_id ? map.get(cur.parent_id) : null }
  return names.reverse().join(' / ')
})
const tempFolderPath = computed(() => {
  if (!tempSelectedFolderId.value) return ''
  const map = new Map(folderStore.flat.map(f => [f.id, f]))
  const names = []
  let cur = map.get(tempSelectedFolderId.value)
  while (cur) { names.push(cur.name); cur = cur.parent_id ? map.get(cur.parent_id) : null }
  return names.reverse().join(' / ')
})
const openFolderPicker = async () => {
  if (!folderStore.flat.length) await folderStore.load()
  tempSelectedFolderId.value = formFolderId.value || selectedFolderId.value || folderStore.flat.find(f => f.name==='收集箱' && (f.parent_id==null))?.id || null
  pickFolderOpen.value = true
}
const onPickSelect = (id) => { tempSelectedFolderId.value = id }
const closeFolderPicker = () => { pickFolderOpen.value = false }
const confirmFolderPicker = () => { if (tempSelectedFolderId.value) { formFolderId.value = tempSelectedFolderId.value } ; pickFolderOpen.value = false }

const load = async () => {
  const params = { folder_id: (selectedFolderId.value && selectedFolderId.value !== 'trash') ? selectedFolderId.value : undefined }
  if (selectedFolderId.value === 'trash') params.trash = true
  const res = await api.get('/api/knowledge/', { params })
  list.value = res.data
}

const restore = async (id) => {
  if (!confirm('确定要还原吗？')) return
  await api.post(`/api/knowledge/${id}/restore`)
  await load()
}
const hardDelete = async (id) => {
  if (!confirm('确定要彻底删除吗？此操作不可恢复！')) return
  await api.delete(`/api/knowledge/${id}/hard`)
  await load()
}
const emptyTrash = async () => {
  if (!confirm('确定要清空草稿箱吗？所有项目将被永久删除！')) return
  await api.delete('/api/knowledge/trash/empty')
  await load()
}

const ensureInboxFolder = async () => {
  if (!folderStore.flat.length) await folderStore.load()
  let inbox = folderStore.flat.find(f => f.name === '收集箱' && (f.parent_id == null))
  if (!inbox) {
    await folderStore.create('收集箱', null)
    await folderStore.load()
    inbox = folderStore.flat.find(f => f.name === '收集箱' && (f.parent_id == null))
  }
  return inbox?.id || null
}

// ====== 新建/编辑 知识点（对话框）逻辑 ======
const addCard = async () => {
  const id = Date.now() + Math.random().toString(36).slice(2,6)
  const current = qaCards.value.find(c => c.active)
  if (current) { current.active = false }
  const card = { id, question: '', answerHtml: '', active: true }
  qaCards.value.push(card)
}
const removeCard = (idx) => {
  const card = qaCards.value[idx]
  if (!card) return
  qaCards.value.splice(idx, 1)
}
const activateCard = async (idx) => {
  const target = qaCards.value[idx]
  if (!target) return
  const current = qaCards.value.find(c => c.active)
  if (current && current !== target) { current.active = false }
  target.active = true
}
const collapseCard = (idx) => {
  const target = qaCards.value[idx]; if (!target) return
  if (target.active) { target.active = false }
}

const openNew = async () => {
  form.value = { id: null, title: '', summary: '', body: '' }
  kpName.value = ''
  kpDesc.value = ''
  qaCards.value = []
  await addCard()
  const inboxId = await ensureInboxFolder()
  formFolderId.value = selectedFolderId.value || inboxId
  show.value = true
}
const edit = async (k) => {
  form.value = { id: k.id, title: k.title, summary: k.summary, body: k.body }
  // 简单填充名称/描述
  kpName.value = k.title || ''
  kpDesc.value = k.summary || ''
  qaCards.value = []
  await addCard()
  show.value = true
}
const close = () => { show.value = false }
const submit = async () => {
  // 组装多问题卡片结构
  const sections = qaCards.value
    .filter(c => (c.question || '').trim() || (c.answerHtml || '').trim())
    .map(c => `
      <section class="qa" data-id="${c.id}">
        <h3>${(c.question || '').replace(/</g,'&lt;').replace(/>/g,'&gt;')}</h3>
        ${c.answerHtml || ''}
      </section>
    `)
    .join('\n')
  const bodyHtml = sections
  const payload = { title: kpName.value || form.value.title, summary: kpDesc.value || form.value.summary, body: bodyHtml.trim() }
  if (!payload.title) return
  try {
    if (form.value.id) {
      await api.put(`/api/knowledge/${form.value.id}`, payload)
    } else {
      const k = await api.post('/api/knowledge/', payload)
      if (formFolderId.value) {
        await api.post(`/api/knowledge/${k.data.id}/folder`, { folder_id: formFolderId.value })
      }
    }
    close()
    await load()
    try { await folderStore.load() } catch {}
  } catch (e) {
    alert((e?.response?.data?.detail) || '保存失败，请重新登录后重试')
  }
}

// ====== 知识点详情抽屉（右侧）逻辑 ======
const detailOpen = ref(false)
const detailId = ref(null)
const dName = ref('')
const dDesc = ref('')
const dCards = ref([]) // { id, question, answerHtml, active }

const parseBody = (html) => {
  const res = { cards: [] }
  try {
    const div = document.createElement('div'); div.innerHTML = html || ''
    div.querySelectorAll('section.qa').forEach((sec) => {
      const h = sec.querySelector('h3')
      const question = (h?.textContent || '').trim()
      if (h) h.remove()
      const answerHtml = sec.innerHTML.trim()
      const id = sec.getAttribute('data-id') || `card-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      res.cards.push({ id, question, answerHtml, active: false })
    })
  } catch {}
  return res
}

const openKnowledgeDetail = async (k) => {
  try {
    const res = await api.get(`/api/knowledge/${k.id}`)
    const item = res.data
    detailId.value = item.id
    dName.value = item.title || ''
    dDesc.value = item.summary || ''
    const parsed = parseBody(item.body || '')
    
    // 确保每个卡片都有唯一的ID
    const stats = item.review_stats || {}
    dCards.value = parsed.cards.length ? parsed.cards.map(card => ({
      ...card,
      active: false, // Default collapsed
      review_stats: stats[card.id] || null
    })) : []
    
    detailOpen.value = true
    
    // No longer auto-activate first card
  } catch (e) { 
    console.error('加载知识点失败:', e)
    alert('加载知识点失败，请重试') 
  }
}

// 编辑器就绪回调
const onEditorReady = (card) => {
  // 确保内容正确设置
  nextTick(() => {
    const editorId = `answer-editor-${card.id}`
    const editor = window.tinymce?.get(editorId)
    if (editor && card.answerHtml) {
      editor.setContent(card.answerHtml, { format: 'raw' })
      editor.undoManager.clear()
      editor.nodeChanged()
    }
  })
}
const dAddCard = async () => {
  const id = Date.now() + Math.random().toString(36).slice(2,6)
  const current = dCards.value.find(c => c.active)
  if (current) { current.active = false }
  const card = { id, question: '', answerHtml: '', active: true }
  dCards.value.push(card)
}
const dRemoveCard = (idx) => {
  if (!confirm('确认删除该问题卡片？')) return
  const card = dCards.value[idx]; if (!card) return
  dCards.value.splice(idx, 1)
}
const dActivateCard = async (idx) => {
  const target = dCards.value[idx]; if (!target) return
  // Don't auto-collapse others, allow multiple open? Or keep single open?
  // User asked for "default collapse all", implies user opens them manually.
  // Let's keep single open for simplicity/focus, or toggle.
  // Let's implement toggle logic in dToggleCard, and here just activate if clicked body (if we want click-to-expand)
  // But the click handler is on the header.
  // So dActivateCard is called when header is clicked.
  
  // If already active, do nothing (toggle handles close)
  if (target.active) return
  
  const current = dCards.value.find(c => c.active)
  if (current && current !== target) { current.active = false }
  target.active = true
}
const dCollapseCard = (idx) => {
  const target = dCards.value[idx]; if (!target) return
  if (target.active) { target.active = false }
}
const closeDetail = () => { detailOpen.value = false }
const saveDetail = async () => {
  const escapeHtml = (text) => {
    const str = text || ''
    return str.split('<').join('&lt;').split('>').join('&gt;')
  }
  
  const sections = dCards.value
    .filter(c => (c.question || '').trim() || (c.answerHtml || '').trim())
    .map(c => `
      <section class="qa" data-id="${c.id}">
        <h3>${escapeHtml(c.question)}</h3>
        ${c.answerHtml || ''}
      </section>
    `)
    .join('\n')
  const bodyHtml = sections
  const payload = { title: dName.value, summary: dDesc.value, body: bodyHtml.trim() }
  if (!detailId.value || !payload.title) return
  try {
    await api.put(`/api/knowledge/${detailId.value}` , payload)
    closeDetail(); await load(); try { await folderStore.load() } catch {}
  } catch (e) { alert((e?.response?.data?.detail) || '保存失败') }
}

const remove = async (id) => {
  if (!confirm('确认删除该知识点？')) return
  await api.delete(`/api/knowledge/${id}`)
  await load()
  try { await folderStore.load() } catch {}
}

const onFolderSelect = async (id) => { selectedFolderId.value = id; await load() }
const onFolderDrop = async ({ folderId, knowledgeId }) => {
  await api.post(`/api/knowledge/${knowledgeId}/folder`, { folder_id: folderId })
  await load(); try { await folderStore.load() } catch {}
}
const onDragStart = (k, e) => { try { e.dataTransfer.setData('text/knowledge-id', String(k.id)) } catch {} }

// Card Drag & Drop
const onCardDragStart = (idx, e) => {
  e.dataTransfer.setData('text/card-idx', String(idx))
  e.dataTransfer.effectAllowed = 'move'
}
const onCardDrop = (targetIdx, e) => {
  const srcIdx = parseInt(e.dataTransfer.getData('text/card-idx'))
  if (isNaN(srcIdx) || srcIdx === targetIdx) return
  const item = dCards.value[srcIdx]
  dCards.value.splice(srcIdx, 1)
  dCards.value.splice(targetIdx, 0, item)
}
const dToggleCard = (idx) => {
  const card = dCards.value[idx]
  if (card) {
      if (!card.active) {
          // Close others if opening one? Or allow multiple?
          // Let's close others to keep it clean like before
          const current = dCards.value.find(c => c.active)
          if (current && current !== card) current.active = false
      }
      card.active = !card.active
  }
}

// row 'more' menu state and handlers
const openMenuId = ref(null)
const toggleRowMenu = (id) => { openMenuId.value = openMenuId.value === id ? null : id }
const closeRowMenu = () => { openMenuId.value = null }
if (typeof window !== 'undefined') {
  const onDocClick = () => { openMenuId.value = null }
  onMounted(() => window.addEventListener('click', onDocClick))
  onBeforeUnmount(() => window.removeEventListener('click', onDocClick))
}
const moveToFolder = async (kid) => {
  const name = prompt('移动到目录（输入名称，大小写完全匹配；留空=移出目录）：')
  let folderId = null
  if (name) {
    const f = folderStore.flat.find(x => x.name === name)
    if (!f) { alert('未找到同名目录'); return }
    folderId = f.id
  }
  await api.post(`/api/knowledge/${kid}/folder`, { folder_id: folderId })
  await load(); await folderStore.load()
}

// Add to Review Logic
const showAddToReview = ref(false)
const reviewCard = ref(null)
const reviewPlanType = ref('ebbinghaus')
const reviewCustomInterval = ref(1)

const openAddToReview = (card) => {
  reviewCard.value = card
  showAddToReview.value = true
}
const closeAddToReview = () => {
  showAddToReview.value = false
  reviewCard.value = null
}
const confirmAddToReview = async () => {
  if (!reviewCard.value || !detailId.value) return
  
  const payload = {
    knowledge_id: detailId.value,
    card_ids: [reviewCard.value.id],
    plan_type: reviewPlanType.value,
    custom_interval: reviewPlanType.value === 'custom' ? reviewCustomInterval.value : undefined
  }
  
  try {
    await api.post('/api/reviews/plan', payload)
    closeAddToReview()
    alert('已加入复盘计划')
    // Refresh to update stats
    const res = await api.get(`/api/knowledge/${detailId.value}`)
    const stats = res.data.review_stats || {}
    dCards.value.forEach(c => {
      c.review_stats = stats[c.id] || null
    })
  } catch (e) {
    alert('添加失败')
    alert('添加失败')
  }
}

// Brush & History Logic
const brushOpen = ref(false)
const openBrush = () => { brushOpen.value = true }

const historyOpen = ref(false)
const historyCardId = ref(null)
const openHistory = (card) => {
  historyCardId.value = card.id
  historyOpen.value = true
}

import { useRoute } from 'vue-router'
const route = useRoute()

onMounted(async () => {
  await folderStore.load()
  await ensureInboxFolder()
  await folderStore.load()
  await load()
  
  // Handle jump from Reviews
  if (route.query.id) {
    const kid = parseInt(route.query.id)
    const k = list.value.find(i => i.id === kid)
    if (k) {
      await openKnowledgeDetail(k)
      if (route.query.card) {
        const idx = dCards.value.findIndex(c => c.id === route.query.card)
        if (idx !== -1) {
          await nextTick()
          dActivateCard(idx)
          // Scroll to card?
          const el = document.querySelector(`[data-id="${route.query.card}"]`)
          if (el) el.scrollIntoView({ behavior: 'smooth' })
        }
      }
    }
  }
})

// utils: strip html and decode entities for summary preview
const stripHtml = (html) => {
  try {
    const div = document.createElement('div')
    div.innerHTML = html || ''
    const text = div.textContent || div.innerText || ''
    return text.replace(/\u00A0/g, ' ').replace(/\s+/g, ' ').trim()
  } catch { return html || '' }
}
</script>

<style>
.drawer-slide-enter-active, .drawer-slide-leave-active { transition: transform .22s ease, opacity .22s ease; }
.drawer-slide-enter-from, .drawer-slide-leave-to { opacity: 0; }
.drawer-slide-enter-from .absolute.right-0, .drawer-slide-leave-to .absolute.right-0 { transform: translateX(100%); }
</style>

<style>
@import "https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css";
</style>
